package listener;

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.ArticleService;
import bean.Article;

@WebListener
public class AppInitListener implements ServletContextListener {
    private static final Logger log = LoggerFactory.getLogger(AppInitListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("应用启动，执行初始化逻辑");
        try {
            ArticleService service = new ArticleService();
            if (service.listAll().isEmpty()) {
                for (int i = 1; i <= 10; i++) {
                    Article a = new Article();
                    a.setTitle("初始化文章 " + i);
                    a.setContent("<p>这是系统初始化生成的文章，用于满足最少10篇的要求。</p>");
                    a.setTags("初始化,系统");
                    service.add(a);
                }
                log.info("已初始化10篇文章");
            }
        } catch (Exception e) {
            // 数据库不可用时跳过初始化
            log.warn("初始化文章失败，可能是数据库未准备好：{}", e.getMessage());
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("应用关闭，清理资源");
    }
}